"use client";

import { useEffect, useState } from 'react';
import { Eye } from 'lucide-react';
import { useLanguage } from '@/context/language-provider';

interface VisitCountProps {
  type: 'homepage' | 'exam';
  grade?: string;
  examName?: string;
  examDate?: string;
  className?: string;
}

export default function VisitCount({ type, grade, examName, examDate, className = '' }: VisitCountProps) {
  const [visits, setVisits] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(true);
  const { language, isInternational } = useLanguage();

  useEffect(() => {
    async function fetchVisits() {
      try {
        if (type === 'homepage') {
          // 添加国际化参数
          const url = isInternational ? '/api/metrics?int=true' : '/api/metrics';
          const response = await fetch(url);
          const data = await response.json();
          setVisits(data.homepageVisits || 0);
        } else if (type === 'exam' && examName) {
          // 构建查询参数
          const params = new URLSearchParams();
          
          if (grade && examDate) {
            // 处理年级格式：将"2022级"这种格式处理为"2022"
            let processedGrade = grade;
            if (processedGrade.includes("级")) {
              processedGrade = processedGrade.replace("级", "");
            }
            
            // 如果有完整信息，使用新的参数格式
            params.append('grade', processedGrade);
            params.append('examName', examName);
            params.append('examDate', examDate);
            
            console.log(`VisitCount 请求参数: grade=${processedGrade}, examName=${examName}, examDate=${examDate}`);
          } else {
            // 只有考试名称时，使用examId参数
            params.append('examId', examName);
            console.log(`VisitCount 请求参数: examId=${examName}`);
          }
          
          // 添加国际化参数
          if (isInternational) {
            params.append('int', 'true');
          }
          
          console.log(`发送请求: /api/metrics?${params.toString()}`);
          const response = await fetch(`/api/metrics?${params.toString()}`);
          const data = await response.json();
          console.log('收到响应数据:', data);
          setVisits(data.visits || 0);
        }
      } catch (error) {
        console.error('获取访问量出错:', error);
      } finally {
        setLoading(false);
      }
    }

    fetchVisits();
  }, [type, grade, examName, examDate, isInternational]);

  // 如果正在加载或访问量为0，则不显示
  if (loading || (type === 'exam' && visits <= 0)) {
    return null;
  }

  return (
    <div className={`flex items-center gap-1 text-sm ${className}`}>
      <Eye className="h-3.5 w-3.5" />
      <span>
        {type === 'homepage' 
          ? language === "zh" 
            ? `${visits+1} 次访问` 
            : `${visits+1} visits`
          : language === "zh"
            ? `${visits} 人想看`
            : `${visits} want to see`}
      </span>
    </div>
  );
} 